package com.zirenx.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.upload.UploadFile;
import com.zirenx.annotation.RouteMapping;
import com.zirenx.common.controller.BaseController;
import com.zirenx.common.controller.IController;
import com.zirenx.common.exception.MessageException;
import com.zirenx.sys.model.SysDept;
import com.zirenx.sys.model.SysDict;
import com.zirenx.sys.model.SysRole;
import com.zirenx.sys.model.SysUser;
import com.zirenx.sys.service.SysDictService;
import com.zirenx.sys.service.SysRoleService;
import com.zirenx.sys.service.SysUserRoleService;
import com.zirenx.sys.service.SysUserService;
import com.zirenx.utils.*;

import java.util.List;

@RouteMapping("/sys/user")
public class SysUserController extends BaseController implements IController{
	private static final Log log = Log.getLog(SysUserController.class);
	
	@Inject
	SysUserService sysUserService;
	@Inject
	SysDictService sysDictService;
	@Inject
	SysRoleService sysRoleService;
	@Inject
	SysUserRoleService sysUserRoleService;

	
	public void index() {
		render("index.html");
	}
	
	public void add() {
		setAttr("bean", new SysUser());
		setAttr("roleList",sysRoleService.getList());
	}
	
	public void edit() {
		SysUser bean = sysUserService.findById(get("id"));
		SysDept dept = new SysDept();
		if (bean.getDeptId()!=null){
			dept = dept.findById(bean.getDeptId());
		}

		setAttr("bean", bean);
		setAttr("dept", dept);

		setAttr("roleList",sysRoleService.getList());
		List roleIds = sysUserRoleService.getRoleIds(bean.getId());
		setAttr("roleIds",roleIds);
	}
	
	public void save() {
		R r = R.ok();
		try {
			getBean(SysUser.class,"bean").save();
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		renderJson(r);
	}
	
	public void update() {
		R r = R.ok();
		try {
            SysUser bean = getBean(SysUser.class, "bean");
            //原数据
            SysUser sysUser = bean.findById(bean.getId());

            if (StringUtils.isEmpty(bean.getPassword())){
                bean.setPassword(sysUser.getPassword());
            }else {
                String password = MD5Utils.encrypt(bean.getUsername(), bean.getPassword());//加密
                bean.setPassword(password);
            }

            bean.update();
            String[] roleIds = getParaValues("roleIds");
            //清空原用户角色
            sysUserRoleService.batchRemove(bean.getId().toString());
            //保存新的用户角色
            sysUserRoleService.batchSave(bean.getId().toString(),roleIds);
        } catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		renderJson(r);
	}
	
	public void remove() {
		R r = R.ok();
		try {
			sysUserService.delete(getPara());
			renderJson(R.ok());
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		renderJson(r);
	}
	
	public void dataAjax() {
		R r = R.ok();
		try {
			SysUser bean = getBean(SysUser.class,"bean");

			SqlPara sqlPara = new SqlPara();
			String sql = "select * from " + bean.getTableName() + " bean where 1=1 ";

			sql += appendSearch(sqlPara);
			sql += " order by bean.id desc";
			sqlPara.setSql(sql);

			Page<SysUser> p = bean.paginate(getPageNumber(), getPageSize(), sqlPara);

			List<SysUser> list = p.getList();
			for (SysUser sysUser : list) {
				if(sysUser.getStatus()!=null) {
					sysUser.setStatusName(SysUser.StatusEnum.getByValue(sysUser.getStatus().intValue()).getName());
				}
			}
			r.put("rows", list);
			r.put("total", p.getTotalRow());
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error(); 
		}
		JSONObject json = new JSONObject(r);
		renderJson(r);
	}
	
	public void batchRemove() {
		R r = R.ok();
		try {
			sysUserService.batchRemove(getParaValues("ids"));
			renderJson(R.ok());
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		renderJson(r);
	}
	
	/**
	  *  个人资料
	 */
	public void personal() {
		SysUser user = SysUserUtils.getUser(getRequest());
		List<SysDict> sexList = sysDictService.getSexList();

		setAttr("bean",user);
		setAttr("sexList",sexList);
		render("personal.html");
	}
	
	/**
	 * 个人资料修改
	 */
	public void updatePeronal() {
		R r = R.ok();
		try {
			SysUser bean = getBean(SysUser.class,"bean");
			if(!bean.update()){
				log.warn("个人资料修改失败。。。");
			}else {
				SysUserUtils.setUser(bean, getRequest());
			}
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		renderJson(r);
	}
	
	/**
	 * 上传头像
	 */
	public void uploadImg() {
		R r = R.ok();
		UploadFile uploadFile = null;
		try {
			uploadFile = getFile("avatar_file");
			String avatarData = get("avatar_data");
			sysUserService.uploadImg(uploadFile,avatarData,SysUserUtils.getUserId(getRequest()),getRequest());
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		if(uploadFile!=null) {
			uploadFile.getFile().delete();	//删除临时文件
		}
		renderJson(r);
	}
	
	/**
	 * 重置密码
	 */
	public void resetPwd() {
		R r = R.ok();
		try {
			String pwdOld = get("pwdOld");		//原密码
			String pwdNew = get("pwdNew");		//新密码
			String confirm_password = get("confirm_password");	//确认密码
			SysUser bean = SysUserUtils.getUser(getRequest());
			
			if(StringUtils.isEmpty(pwdOld)) {
				throw new MessageException("请输入原密码");
			}
			if(StringUtils.isEmpty(pwdNew)) {
				throw new MessageException("请输入新密码");
			}
			if(StringUtils.isEmpty(confirm_password)) {
				throw new MessageException("请输入确认密码");
			}
			if(!bean.getPassword().equals(MD5Utils.encrypt(bean.getUsername(), pwdOld))) {
				throw new MessageException("原密码错误");
			}
			if(!pwdNew.equals(confirm_password)) {
				throw new MessageException("新密码与确认密码不一致");
			}
			bean.setPassword(MD5Utils.encrypt(bean.getUsername(), pwdNew));
			bean.setGmtModified(DateUtils.getCurrentTime());
			if(!bean.update()){
				log.warn("重置密码失败。。。");
			}else {
				SysUserUtils.setUser(bean, getRequest());
			}
		} catch (MessageException e) {
			r = R.error();
			r.put("msg", e.getMessage());
		} catch (Exception e) {
			LogUtils.error(this.getClass(),e);
			r = R.error();
		}
		renderJson(r);
	}
}
